package com.tg.app.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.joooonho.SelectableRoundedImageView;
import com.tg.app.R;
import com.tg.app.activity.device.CameraViewActivity;
import com.tg.app.bean.DevicePresetPoints;
import com.tg.app.camera.Camera;
import com.tg.app.camera.CameraHelper;
import com.tg.app.camera.Cs2Camera;
import com.tg.app.camera.PrepositionProxy;
import com.tg.app.util.LocalThumbnailUtils;
import com.tg.app.util.ObjectBoxUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.android.TGToast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PrePositionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    public static final String TAG = PrePositionAdapter.class.getSimpleName();
    public static final String MODE_DIALOG = "mode_dialog";
    public static final String MODE_SWITCH = "mode_switch";
    public static int IMAGE_WIDTH = 110;
    public static int IMAGE_HEIGHT = 67;
    public static final int ACTION_ADD = 0;
    public static final int ACTION_ITEM = 1;
    public static final float BORDER_WIDTH_DP = 2;

    protected Camera mCamera;
    protected final List<DevicePresetPoints> prePositions = new ArrayList<>();
    protected final List<DevicePresetPoints> selectedPresetPoints = new ArrayList<>();
    protected final Context context;
    protected boolean isEditEnable = false;
    protected final PrePositionListener mPrePositionListener;
    protected int mIdleTime = 30;
    protected int mWatchPosNumber = -1;
    protected int mSelectPosition = -1;


    public int getWatchPosNumber() {
        return mWatchPosNumber;
    }
    public void setWatchPosInfo(int watchPosNumber, int idleTime) {
        mWatchPosNumber = watchPosNumber;
        if (mWatchPosNumber == -1){
            mIdleTime = 30;
        }else {
            mIdleTime = idleTime;
        }
    }

    public int getSelectPosition() {
        return mSelectPosition;
    }
    public int getIdleTime() {
        return mIdleTime;
    }
    public void setCamera(Camera camera){
        this.mCamera = camera;
    }
    public String getMode(){
        return MODE_DIALOG;
    }
    public List<DevicePresetPoints> getSelectedPresetPoints() {
        return selectedPresetPoints;
    }

    public List<DevicePresetPoints> getPrePositions() {
        return prePositions;
    }

    public void clearSelectedPresetPoints(){
        selectedPresetPoints.clear();
    }


    public boolean isExistDevicePresetPoints(int num) {
        for (DevicePresetPoints p : prePositions) {
            if (p.num == num){
                return true;
            }
        }
        return false;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void clearPointFromSelected(){
        for (DevicePresetPoints p : selectedPresetPoints){
            TGLog.d(TAG,"number  = " + p.num + "mWatchPosNumber = " + mWatchPosNumber);
            if (mWatchPosNumber == p.num){
                mWatchPosNumber = -1;
                mIdleTime = 30;
            }
            prePositions.remove(p);

        }
        notifyDataSetChanged();
    }

    public int getNewNum() {
        List<Integer> numList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
        for (DevicePresetPoints p : prePositions) {
            Integer integer = p.num;
            TGLog.d(TAG,"getNewNum " + integer);
            numList.remove(integer);
        }
        return numList.get(0);
    }


    public boolean isEditEnable() {
        return isEditEnable;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setData(String uuid){
        List<DevicePresetPoints> points = ObjectBoxUtil.getDevicePresetPoints(uuid);
        if (points!=null){
            prePositions.addAll(points);
            notifyDataSetChanged();
        }
    }

    public void setData(List<DevicePresetPoints> list){
        prePositions.clear();
        prePositions.addAll(list);
    }

    public void addData(DevicePresetPoints devicePresetPoints){
        prePositions.add(devicePresetPoints);
        if (devicePresetPoints != null){
            if (StringUtils.equalsIgnoreCase(getMode(), MODE_SWITCH)){
                mSelectPosition = devicePresetPoints.num - 1;
            }else{
                mSelectPosition = prePositions.size() - 1;
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setEditEnable(boolean editEnable) {
        isEditEnable = editEnable;
        if (isEditEnable){
            mSelectPosition = -1;
        }
        notifyDataSetChanged();
    }

    public PrePositionAdapter(Context context, PrePositionListener listener) {
        this.context = context;
        mPrePositionListener = listener;
        int w = context.getResources().getDisplayMetrics().widthPixels - DimenUtil.dp2px(context, 44);
        w = (int)DimenUtil.px2dp(context, w);
        PrePositionAdapter.IMAGE_WIDTH = w / 3;
        PrePositionAdapter.IMAGE_HEIGHT = PrePositionAdapter.IMAGE_WIDTH * 67 / 110;
        TGLog.d(TAG,"Width = " + PrePositionAdapter.IMAGE_WIDTH + ", height = " + PrePositionAdapter.IMAGE_HEIGHT);
        @SuppressLint("NotifyDataSetChanged") PrePositionImageListener prePositionImageListener = num -> TGThreadPool.executeOnUiThread(() -> {
            TGLog.d("num = " + num);
            CameraViewActivity activity = (CameraViewActivity) context;
            Bitmap bitmap = activity.getPlayerView().getTextureViewBmp();
            DevicePresetPoints devicePresetPoints = null;
            int i = 0;
            for (; i < prePositions.size(); i++) {
                if (prePositions.get(i).num == num) {
                    devicePresetPoints = prePositions.get(i);
                    break;
                }
            }

            if (devicePresetPoints != null) {
                saveImage(bitmap, devicePresetPoints);
                Activity activity1 = TGApplicationBase.getAppLifecycleCallbacks().getCurrentActivity();
                if (activity1 instanceof CameraViewActivity){
                    TGToast.showToast(R.string.txt_arrived_position);
                }

                notifyDataSetChanged();
            }

            TGLog.d("mSelectPosition = " + mSelectPosition);
        });
        if (StringUtils.equalsIgnoreCase(getMode(), MODE_SWITCH)){
            TGApplicationBase.getInstance().putGlobalObject(PrePositionFragmentAdapter.TAG, prePositionImageListener);
        }else{
            TGApplicationBase.getInstance().putGlobalObject(PrePositionDialogAdapter.TAG, prePositionImageListener);
        }
        if (context instanceof CameraViewActivity) {
            CameraViewActivity cameraViewActivity = (CameraViewActivity) context;
            if (cameraViewActivity.getCamera() instanceof Cs2Camera) {
                PrepositionProxy.attach((Cs2Camera) cameraViewActivity.getCamera());
            }
        }

    }


    protected @LayoutRes
    int getAddResourceId(){
        return R.layout.layout_fragment_pre_position_add;
    }

    protected @LayoutRes int getItemResourceId(){
        return R.layout.layout_fragment_pre_position_item;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        TGLog.d("viewType = " + viewType);
        if (viewType == ACTION_ITEM) {
            View view = LayoutInflater.from(context).inflate(getItemResourceId(), parent, false);
            return new PrePositionViewHolder(view, getMode());
        }
        View view = LayoutInflater.from(context).inflate(getAddResourceId(), parent, false);
        return new PrePositionAddViewHolder(view, getMode());
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        TGLog.d(TAG,"position = " + position + ", holder = " + holder);
        if (holder instanceof PrePositionAddViewHolder) {
            ((PrePositionAddViewHolder) holder).mTextView.setText(String.valueOf(position+1));
            holder.itemView.setOnClickListener(v -> {
                if (mPrePositionListener != null){
                    mPrePositionListener.click(position);
                }
            });
        } else if (holder instanceof PrePositionViewHolder) {
            prePositionView((PrePositionViewHolder) holder, position);
        }

    }

    private Bitmap getImage(DevicePresetPoints req) {
        String fileName = req.getFileName(mCamera);
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        return LocalThumbnailUtils.getInstance().getBitmap(fileName);
    }

    public void saveImage(Bitmap b, DevicePresetPoints req) {
        if (b != null) {
            String fileName = req.getFileName(mCamera);
            if (StringUtils.isEmpty(fileName)) {
                return;
            }
            LocalThumbnailUtils.getInstance().saveLocalThumbnail(b, fileName);
        }
    }

    public DevicePresetPoints getDevicePresetPoints(int position){
        return prePositions.get(position);
    }

    private void setImageBorder(SelectableRoundedImageView selectableRoundedImageView, float width){
        selectableRoundedImageView.setBorderWidthDP(width);
    }

    private void prePositionView(@NonNull PrePositionViewHolder prePositionViewHolder, int position) {
        DevicePresetPoints prePosition = getDevicePresetPoints(position);
        Bitmap b = getImage(prePosition);
        TGLog.d(TAG,"position = " + prePosition.num);
        TGLog.d(TAG,"position = " + position);
        TGLog.d(TAG,"position.name = " + prePosition.name);
        TGLog.d(TAG,"b = " + b);
        String mode = getMode();
        if (b != null) {
            prePositionViewHolder.imageView.setImageBitmap(b);
        } else {
            @DrawableRes int resId = R.mipmap.fragment_pre_position_item_bg;
            prePositionViewHolder.imageView.setImageResource(resId);
        }
        if (!StringUtils.isEmpty(prePosition.name)) {
            prePositionViewHolder.textView.setText(prePosition.name);
        }
        prePositionViewHolder.tvNumber.setText(String.valueOf(position+1));
        prePositionViewHolder.checkBox.setVisibility(isEditEnable ? View.VISIBLE : View.GONE);
        prePositionViewHolder.checkBox.setChecked(selectedPresetPoints.contains(prePosition));
        if (isEditEnable || mSelectPosition != position){
            prePositionViewHolder.imageView.setSelected(false);
      //    setImageBorder((SelectableRoundedImageView)prePositionViewHolder.imageView, 0);
        }else {
            if (prePositionViewHolder.imageView instanceof SelectableRoundedImageView){
                prePositionViewHolder.imageView.setSelected(true);
                setImageBorder((SelectableRoundedImageView)prePositionViewHolder.imageView, PrePositionAdapter.BORDER_WIDTH_DP);
            }
        }
        boolean show = StringUtils.equalsIgnoreCase(mode, MODE_SWITCH) && mWatchPosNumber == prePosition.num;
        if (prePositionViewHolder.mRelativeLayout != null){
            prePositionViewHolder.mRelativeLayout.setVisibility(show? View.VISIBLE : View.GONE);
        }

        @SuppressLint("NotifyDataSetChanged") View.OnClickListener listener = v -> {
            if (isEditEnable) {
                boolean isChecked = prePositionViewHolder.checkBox.isChecked();
                if (v instanceof ImageView) {
                    isChecked = !isChecked;
                }
                if (isChecked) {
                    if (!selectedPresetPoints.contains(prePosition)) {
                        selectedPresetPoints.add(prePosition);
                    }
                } else {
                    selectedPresetPoints.remove(prePosition);
                }
                notifyItemChanged(position);
                if (mPrePositionListener != null){
                    mPrePositionListener.updateDelStatus();
                }
            } else {
                boolean isMustNotify = false;
                if (v instanceof ImageView) {
                    v.setSelected(true);
                    mSelectPosition = position;
                    if (v instanceof SelectableRoundedImageView){
                        isMustNotify = true;
                        setImageBorder((SelectableRoundedImageView)v, PrePositionAdapter.BORDER_WIDTH_DP);
                    }
                }

                if (!mCamera.isConnected()){
                    TGToast.showToast(R.string.camera_send_failed);
                    if (isMustNotify){
                        notifyDataSetChanged();
                    }
                    return;
                }

                CameraHelper.setPtzPosReq(mCamera, prePosition.pos, 0, prePosition.num);
                String title;
                if (StringUtils.equalsIgnoreCase(mode, MODE_DIALOG)){
                    title = String.format(ResourcesUtil.getString(R.string.txt_turning_position), prePosition.name);
                }else {
                    title = String.format(ResourcesUtil.getString(R.string.txt_turning_position), position + 1);
                }

                TGToast.showToast(title);
                if (isMustNotify){
                    notifyDataSetChanged();
                }
            }
        };
        prePositionViewHolder.imageView.setOnClickListener(listener);
        prePositionViewHolder.checkBox.setOnClickListener(listener);
    }


    @Override
    public int getItemCount() {
        return 6;
    }

    @Override
    public int getItemViewType(int position) {
        if (isEditEnable) return ACTION_ITEM;
        if (position < prePositions.size()){
            return ACTION_ITEM;
        }
        return ACTION_ADD;
    }

    public static class PrePositionAddViewHolder extends RecyclerView.ViewHolder {
        final TextView mTextView;
        public PrePositionAddViewHolder(@NonNull View itemView, @NonNull String mode) {
            super(itemView);
            mTextView = itemView.findViewById(R.id.text);
            ViewGroup.LayoutParams layoutParams = itemView.getLayoutParams();
            layoutParams.width = DimenUtil.dp2px(TGApplicationBase.getApplicationContext(), PrePositionAdapter.IMAGE_WIDTH);
            layoutParams.height = DimenUtil.dp2px(TGApplicationBase.getApplicationContext(), PrePositionAdapter.IMAGE_HEIGHT);
            itemView.setLayoutParams(layoutParams);
            itemView.findViewById(R.id.rl_bkg).setVisibility(StringUtils.equalsIgnoreCase(mode, MODE_SWITCH)? View.VISIBLE : View.GONE);
        }
    }

    public static class PrePositionViewHolder extends RecyclerView.ViewHolder {
        final ImageView imageView;
        final TextView textView;
        final CheckBox checkBox;
        final TextView tvNumber;
        final RelativeLayout mRelativeLayout;

        public PrePositionViewHolder(@NonNull View itemView, @NonNull String mode) {
            super(itemView);
            ViewGroup.LayoutParams layoutParams = itemView.getLayoutParams();
            layoutParams.width = DimenUtil.dp2px(TGApplicationBase.getApplicationContext(), PrePositionAdapter.IMAGE_WIDTH);
            layoutParams.height = DimenUtil.dp2px(TGApplicationBase.getApplicationContext(), PrePositionAdapter.IMAGE_HEIGHT);
            imageView = itemView.findViewById(R.id.pre_position_item_img);
            textView = itemView.findViewById(R.id.pre_position_item_text);
            checkBox = itemView.findViewById(R.id.pre_position_item_checkbox);
            tvNumber = itemView.findViewById(R.id.text);
            mRelativeLayout = itemView.findViewById(R.id.rl_guard);
            if (mRelativeLayout != null){
                itemView.findViewById(R.id.rl_bkg).setVisibility(View.VISIBLE);
            }
            textView.setVisibility(StringUtils.equalsIgnoreCase(mode, MODE_DIALOG)? View.VISIBLE : View.GONE);
            itemView.findViewById(R.id.rl_bkg).setVisibility(StringUtils.equalsIgnoreCase(mode, MODE_SWITCH)? View.VISIBLE : View.GONE);
        }
    }

    public interface PrePositionListener{
        void updateDelStatus();
        void click(int position);
    }

    public interface PrePositionImageListener{
        void updateImage(int num);
    }
}


